﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using DependencyInjectionHelperLib;
using DependencyInjectionHelperLib.Attributes;
using DependencyInjectionHelperLib.Navigation;
using MeterReader.Messages;
using MeterReader.Services;

namespace MeterReader.ViewModels
{
    [DIRegistration]
    public partial class MainWindowViewModel
        : ObservableRecipient,
            IRecipient<NavigateRequestMessage>,
            IRecipient<WorkStatusMessage>,
            IRecipient<FaultMessage>
    {
        private INavigationObjectProvider? _navigationObjectProvider;
        private IDataService? _dataService;

        public MainWindowViewModel() { }

        public MainWindowViewModel(INavigationObjectProvider navigationObjectProvider, IDataService dataService)
        {
            _navigationObjectProvider = navigationObjectProvider;
            _dataService = dataService;
            IsActive = true;
            NavigationObject = _navigationObjectProvider.GetNavigationObject<MetersDataMonitorViewModel>("MetersDataMonitor");
        }

        public void Receive(NavigateRequestMessage message) => NavigationObject = message.ViewModel;

        public void Receive(WorkStatusMessage message) => Working = message.Working;

        public void Receive(FaultMessage message)
        {
            FaultMessage = message.Message;
            IsPopupOpen = true;
        }

        [ObservableProperty]
        private object? _navigationObject;

        [ObservableProperty]
        private bool _working;

        [ObservableProperty]
        private bool? _isPopupOpen = false;

        [ObservableProperty]
        private string? _faultMessage;

        [RelayCommand]
        private void StopApp() => _dataService!.StopPeriodicRead();
    }
}
